<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NSpace align="center">
          流程备注:
          <NInput
            v-model:value="paginationReactive.remark"
            placeholder="请输入流程备注"
            clearable
            class="commonWidth"
          ></NInput>
          流程类型:
          <NSelect
            :options="parentCodeList"
            placeholder="请选择流程类型"
            clearable
            style="width: 200rem"
            label-field="name"
            value-field="value"
            v-model:value="paginationReactive.functionCode"
            class="commonWidth"
            filterable
            :render-option="renderOption"
          />
          申请日期:
          <NDatePicker
            input-readonly
            placeholder="请选择申请日期"
            v-model:formatted-value="range"
            clearable
            type="daterange"
            style="width: 280rem"
          ></NDatePicker>
          申请人:
          <NInput
            v-model:value="paginationReactive.applicant"
            placeholder="请输入申请人"
            clearable
            class="commonWidth"
          ></NInput>
          <NButton
            type="primary"
            style="width: 78rem"
            ghost
            @click="searchTable"
          >
            查询
          </NButton>
        </NSpace>
        <NSpace align="center">
          <NButton
            type="primary"
            style="width: 110rem"
            @click="agreeDispose(true)"
            :disabled="tableData?.length == 0"
            ghost
          >
            批量审批同意
          </NButton>
          <NButton
            type="error"
            style="width: 110rem"
            @click="agreeDispose(false)"
            :disabled="tableData?.length == 0"
            ghost
          >
            批量审批拒绝
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable
        v-bind="props"
        :bordered="false"
        :columns="columns"
        :data="tableData"
        :pagination="false"
        :loading="tableLoading"
        :row-key="rowKeys"
        :checked-row-keys="dataListSelections"
        striped
        @update:checked-row-keys="selectionChangeHandle"
      />
    </template>

    <template #pagination>
      <NPagination
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker
        show-quick-jumper
        :suffix="() => '页'"
      >
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal
    :auto-focus="false"
    v-model:show="contentVisible"
    @close="contentVisible = false"
  >
    <VDialogContent
      @close="onModalClosed"
      @submit="submit"
      title="审批"
    >
      <!-- <div style="display: flex;margin-bottom: 10px;height: 30px;line-height: 30px;" v-if="isNeedProcurementMethod()">
        <div style="width: 70px;text-align: right;">采购方式:</div>
        <NSelect style="width: 300rem;margin-left: 10rem;" clearable :options="ProcurementMethodOptions" v-model:value="procurementMethod"/>
      </div> -->
      <div style="display: flex">
        <div style="width: 70px; text-align: right; height: 30px; line-height: 30px">备注:</div>
        <NInput
          v-model:value="opinions"
          placeholder="请输入备注"
          clearable
          type="textarea"
          style="width: 300rem; height: 200rem; margin-left: 10rem"
        />
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { h, reactive, onMounted, ref, watch, type VNode, onDeactivated } from 'vue'
import {
  NSpace,
  NButton,
  NDataTable,
  NPagination,
  NSelect,
  useMessage,
  NInput,
  NDatePicker,
  NModal,
  NTooltip
} from 'naive-ui'
import type { DataTableColumns, SelectOption } from 'naive-ui'
import TableView from '@/components/TableView.vue'
import router from '@/router'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import type { UserModel } from '@/api/userCenter'
import { useRoute } from 'vue-router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { userCenterStore } from '@/stores/notice'
import { useViewerStore } from '@/views/OA/Common/store'
import { RecordType } from '@/router/utils'
import useFlush from '@/hooks/useFlush'
import { ProcurementMethodOptions } from '@/enums/index'

useFlush('flushDjRecord', () => getExamineList())

const useOAStore = useViewerStore()
const useStore = userCenterStore()
const message = useMessage()
const route = useRoute()

const isNeedProcurementMethod = () => {
  return RecordType.isProcure2(approveRecordCode.value) && resultFlag.value
}
const rowKeys: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    type: 'selection',
    fixed: 'left',
    width: 30,
    align: useOAStore.isCenter,
    disabled: (rowData: any, rowIndex: number) => {
      return rowData.otherParamFlag || rowData.assigneeIdentifying
    }
  },
  {
    title: '部门',
    key: 'deptName',
    width: 80,
    align: useOAStore.isCenter
  },
  {
    title: '申请人',
    key: 'createBy',
    width: 40,
    align: useOAStore.isCenter
  },
  {
    title: '流程类型',
    key: 'codeName',
    width: 100,
    align: useOAStore.isCenter
  },
  {
    title: '流程备注',
    key: 'remark',
    width: 200,
    align: useOAStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: 'max-width:200rem'
      }
    }
  },
  {
    title: '申请时间',
    key: 'createTime',
    width: 100,
    align: useOAStore.isCenter
  },
  {
    title: '流程状态',
    key: 'fromStatusCode',
    width: 40,
    align: useOAStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    align: useOAStore.isCenter,
    width: 100,
    fixed: 'right',
    render: (row: any) => [
      !row.otherParamFlag &&
        !row.assigneeIdentifying && // 信访加签
        h(
          NButton,
          {
            type: 'primary',
            quaternary: true,
            onClick: () => {
              handleApprove(row, true)
            }
          },
          { default: () => '同意' }
        ),
      !row.otherParamFlag &&
        !row.assigneeIdentifying && // 信访加签
        h(
          NButton,
          {
            type: 'error',
            quaternary: true,
            onClick: () => {
              handleApprove(row, false)
            }
          },
          { default: () => '拒绝' }
        ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            RecordType.setRouteNameTypeTrue(row.code)
            const path = jumpRouterList.value.find((it: any) => it.code == row.code)?.routeOne
            if (path) {
              router.push({
                path,
                query: {
                  id: row.resourceId as never,
                  flat: true as never,
                  isApproval: 'true',
                  redirect: router.currentRoute.value.fullPath
                }
              })
            } else {
              message.error('功能正在开发中')
            }
          }
        },
        {
          default: () => '详情'
        }
      )
    ]
  }
]
// 上一页下一页
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 50,
  functionCode: null, //类型
  remark: null, //备注
  applicant: null, //申请人
  startTime: null, //开始时间
  endTime: null, //结束时间
  onChange: (page: number) => {
    paginationReactive.page = page
    getExamineList()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    getExamineList()
  }
})
// select的Tooltip
const renderOption = ({ node, option }: { node: VNode; option: SelectOption }) => {
  return h(
    NTooltip,
    { style: { backgroundColor: '#e1e1e1' } },
    {
      trigger: () => node,
      default: () => option.name
    }
  )
}
// table的key选择
const dataListSelections: any = ref([])
function selectionChangeHandle(_: any) {
  dataListSelections.value = _
}
// 审批同意or拒绝
const agreeDispose = async (flat: any) => {
  resultFlag.value = flat
  flat ? (opinions.value = '同意') : (opinions.value = '拒绝')
  if (dataListSelections.value.length) return (contentVisible.value = true)
  message.error('请最少选择一项数据')
}
/** 弹窗关闭 */
const onModalClosed = () => {
  contentVisible.value = false
  if (isSingeleApprove.value) {
    isSingeleApprove.value = false
    approveRecord.value = ''
    approveRecordCode.value = ''
  }
}
const isSingeleApprove = ref<boolean>(false) // 是否处理单条记录
const approveRecord = ref<string | number>('') // 审批的单条记录
const approveRecordCode = ref<string>('')
/** 处理单条记录的审批 */
const handleApprove = (record: any, flat: boolean) => {
  opinions.value = flat ? '同意' : '拒绝'
  resultFlag.value = flat
  isSingeleApprove.value = true
  approveRecord.value = record.id
  approveRecordCode.value = String(record.code)
  contentVisible.value = true
}
// 提交
const procurementMethod = ref(null) // 采购方式
const opinions = ref()
const resultFlag = ref()
const contentVisible = ref(false)
// 提交审批
const submit = async () => {
  // 此处需要区分是批量处理还是单条处理
  contentVisible.value = false
  tableLoading.value = true
  const request = isSingeleApprove.value
    ? sendRequest<HttpResponse>({
        module: 'dispose',
        api: 'approve',
        override: {
          data: {
            assigneeFlag: false,
            resultFlag: resultFlag.value,
            fromId: approveRecord.value,
            opinions: opinions.value,
            otherParam: null,
            procurementMethod: procurementMethod.value
          }
        }
      })
    : sendRequest<HttpResponse>({
        module: 'userCenter',
        api: 'emaineDispose',
        override: {
          data: {
            resultFlag: resultFlag.value,
            opinions: opinions.value,
            fromId: dataListSelections.value.map((it: any) => it).join(',')
          }
        }
      })
  const [error, res] = await request
  if (error) return message.error(error.message), (tableLoading.value = false)
  if (res.code !== 0) return message.error(res.msg), (tableLoading.value = false)
  message.success(isSingeleApprove.value ? '审批成功' : '批量审批成功')
  if (!isSingeleApprove.value) {
    dataListSelections.value = []
  } else {
    approveRecord.value = ''
    approveRecordCode.value = ''
    isSingeleApprove.value = false
    dataListSelections.value = []
  }
  useStore.getTopCount()
  getExamineList()
}
//流程类型
const parentCodeList: any = ref([])
const getFunction = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'progress',
    api: 'getWorkFlowFunctionCodeList'
  })
  if (error) return
  if (res.code != 0) return
  parentCodeList.value = res.data
}
// 获取列表
const tableData = ref([])
const tableLoading = ref(false)
const getExamineList = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse<UserModel>>({
    module: 'userCenter',
    api: 'emaineList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        functionCode: paginationReactive.functionCode,
        startTime: paginationReactive.startTime,
        applicant: paginationReactive.applicant,
        remark: paginationReactive.remark,
        endTime: paginationReactive.endTime
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  tableData.value = res.data.list
  paginationReactive.itemCount = res.data.totalCount
}
// 查询
const range: any = ref()
const searchTable = () => {
  paginationReactive.page = 1
  paginationReactive.startTime = range.value ? range.value[0] : null
  paginationReactive.endTime = range.value ? range.value[1] : null
  getExamineList()
}
//获取需要跳转的路由
const jumpRouterList: any = ref([])
const getJumpRouterList = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'userCenter',
    api: 'getJumpRoute'
  })
  if (error) return message.error(error.message)
  jumpRouterList.value = res.data
}

onMounted(() => {
  getJumpRouterList()
  getFunction()
})

const keyUpDown = (e: any) => e.key == 'Enter' && ((paginationReactive.page = 1), getExamineList())
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route,
  () => {
    if (route.path == '/OA/UserCenter/Examine') {
      getExamineList()
      window.addEventListener('keyup', keyUpDown, false) // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
.table_pad {
  padding: 10px 20px 15px;
}

.table {
  padding: 29rem 30rem 42rem;
}

.commonWidth {
  width: 150rem;
}
</style>
